﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using hedefgrup.reports.renault.database;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;

namespace hedefgrup.reports.common
{
    public class Report_AudioRecordings : Report_Abstract
    {
        protected override void SetCriteriaList()
        {
            Criterias.Add(new Criteria_EndMonth() { Context = Context });
            Criterias.Add(new Criteria_Network() { Context = Context });
            Criterias.Add(new Criteria_Organization() { Context = Context });
        }

        public override ReportResult GenerateReport()
        {
            ReportResult results = new ReportResult(this);
            Row headerRow = new Row();
            results.HeaderRows.Add(headerRow);
            headerRow.Cells.Add(new Cell() { Text = "Form ID" });
            headerRow.Cells.Add(new Cell() { Text = "Medya" });

            if (Context.CompatibleProjectName == Global.PROJECT_SSRD)
            {
                headerRow.Cells.Add(new Cell() { Text = "YETKİLİ SERVİS" });
                headerRow.Cells.Add(new Cell() { Text = "SATIŞ TARİHİ" });
            }
            else
            {
                headerRow.Cells.Add(new Cell() { Text = "BAYII KODU" });
                headerRow.Cells.Add(new Cell() { Text = "BAYII ADI" });
                headerRow.Cells.Add(new Cell() { Text = "DONEM" });
            }
            headerRow.Cells.Add(new Cell() { Text = "MARKA" });
            headerRow.Cells.Add(new Cell() { Text = "MODEL" });
            headerRow.Cells.Add(new Cell() { Text = "ŞASE" });

            if (Context.CompatibleProjectName != Global.PROJECT_SSRD)
            {
                headerRow.Cells.Add(new Cell() { Text = "AD, SOYAD" });
            }
            else
            {
                headerRow.Cells.Add(new Cell() { Text = "Anketör" });
            }

            if (Context.CompatibleProjectName == Global.PROJECT_QVN2013)
            {
                headerRow.Cells.Add(new Cell() { Text = "SATIS DANIŞMANI" });
                headerRow.Cells.Add(new Cell() { Text = "S18 - " + Context.Questionnaire.GetChild("S18").Text });
                headerRow.Cells.Add(new Cell() { Text = "S17 - " + Context.Questionnaire.GetChild("S17").Text });
            }
            else if (Context.CompatibleProjectName == Global.PROJECT_SATIS_SUREC)
            {
                headerRow.Cells.Add(new Cell() { Text = "SATIS DANIŞMANI" });
                headerRow.Cells.Add(new Cell() { Text = "S2 - " + Context.Questionnaire.GetChild("S2").Text });
                headerRow.Cells.Add(new Cell() { Text = "S8b - " + Context.Questionnaire.GetChild("S8b").Text });
            }
            else if (Context.CompatibleProjectName == Global.PROJECT_SSRD)
            {
                headerRow.Cells.Add(new Cell() { Text = "S3 - " + Context.Questionnaire.GetChild("S3").Text });
                headerRow.Cells.Add(new Cell() { Text = "S10 - " + Context.Questionnaire.GetChild("S10").Text });
            }

            string columnNames =
                Context.CompatibleProjectName == Global.PROJECT_QVN2013 ? "ADSOYAD, SATICI, S19, S18, S17" :
                Context.CompatibleProjectName == Global.PROJECT_SATIS_SUREC ? "ADSOYAD, SATICI, S2, S8b" :
                "SERVIS, S8, S3, S10, ANKETOR";

            DataTable reportData = db.query
            (
                "SELECT IID, " + base.DealerColumn + ", YIL, AY, MARKA, MODEL, SASENO, " + columnNames + " FROM " + Context.TableName + " " +
                GetSqlStatementFilter() +
                " ORDER BY IID ASC",
                GetSqlStatementParameters()
            );

            string applicationPath = Context.ApplicationPath.ToLowerInvariant();
            string audioFilePath = Context.AudioFilesPath;

            string[] allAudioFiles = Directory.GetFiles(audioFilePath, "*.wav", SearchOption.AllDirectories);
            SortedList<string, List<string>> listOfAudioFiles = new SortedList<string, List<string>>();
            foreach (string audioFile in allAudioFiles)
            {
                string audioFileName = Path.GetFileName(audioFile);
                string audioFileNameWithoutExtension = Path.GetFileNameWithoutExtension(audioFileName);
                Match match = Regex.Match(audioFileNameWithoutExtension, "([0-9]{6})_[0-9]+\\-([0-9]+)");
                if (match.Success)
                {
                    string cacheKey = match.Groups[1].Value + "_" + match.Groups[2].Value;
                    if (listOfAudioFiles.ContainsKey(cacheKey))
                    {
                        listOfAudioFiles[cacheKey].Add(audioFile);
                    }
                    else
                    {
                        listOfAudioFiles.Add(cacheKey, new List<string>(new string[] { audioFile }));
                    }
                }
            }
            foreach (DataRow reportRow in reportData.Rows)
            {
                bool shareMyResults =
                    Context.CompatibleProjectName == Global.PROJECT_QVN2013 ? Convert.ToString(reportRow["S19"]) == "1" :
                    Context.CompatibleProjectName == Global.PROJECT_SSRD ? Convert.ToString(reportRow["S8"]) == "1" :
                    true;

                Row recordRow = new Row();
                results.Rows.Add(recordRow);
                string iid = string.Format("{0:0000}{1:00}_{2}", reportRow["YIL"], reportRow["AY"], reportRow["IID"].ToString().Trim()); ;
                string iidFinalValue = null;
                if (listOfAudioFiles.ContainsKey(iid))
                {
                    foreach (string audioFilePart in listOfAudioFiles[iid])
                    {
                        iidFinalValue += string.Format
                        (
                            "<a href='{0}'>{1}</a><br/>",
                            "/" + audioFilePart.ToLowerInvariant().Replace(applicationPath, "").Replace('\\', '/'),
                            "Dinle"
                        );
                    }

                    iidFinalValue = iidFinalValue.Substring(0, iidFinalValue.Length - 5);
                }

                recordRow.Cells.Add(new Cell() { Text = iid, TextAlign = "left" });
                recordRow.Cells.Add(new Cell() { Text = (shareMyResults && iid != iidFinalValue) ? iidFinalValue : "**********", TextLimit = 1024, TextAlign = "left" });

                if (Context.CompatibleProjectName != Global.PROJECT_SSRD)
                {
                    recordRow.Cells.Add(new DealerCodeCell() { Text = reportRow[base.DealerColumn].ToString().Trim(), TextAlign = "left" });
                    recordRow.Cells.Add(new Cell() { Text = GetDealerName(reportRow[base.DealerColumn].ToString().Trim()), TextAlign = "left" });
                }
                else
                {
                    recordRow.Cells.Add(new DealerCodeCell() { Text = reportRow["SERVIS"].ToString().Trim(), TextAlign = "left" });
                }
                recordRow.Cells.Add(new Cell() { Text = string.Format("{0:0000}{1:00}", reportRow["YIL"], reportRow["AY"]) });
                recordRow.Cells.Add(new Cell() { Text = reportRow["MARKA"].ToString() });
                recordRow.Cells.Add(new Cell() { Text = reportRow["MODEL"].ToString() });
                recordRow.Cells.Add(new Cell() { Text = shareMyResults ? reportRow["SASENO"].ToString() : "**********" });
                if (Context.CompatibleProjectName != Global.PROJECT_SSRD)
                {
                    recordRow.Cells.Add(new Cell() { Text = shareMyResults ? reportRow["ADSOYAD"].ToString() : "**********" });
                    recordRow.Cells.Add(new Cell() { Text = reportRow["SATICI"].ToString() });
                }
                else
                {
                    recordRow.Cells.Add(new Cell() { Text = reportRow["ANKETOR"].ToString() });
                }

                if (Context.CompatibleProjectName == Global.PROJECT_QVN2013)
                {
                    Tree s18 = Context.Questionnaire.GetChild("S18");
                    Tree s17 = Context.Questionnaire.GetChild("S17");
                    string optionString = reportRow["S18"].ToString();
                    Tree option = s18.GetChild(optionString);
                    recordRow.Cells.Add(new Cell() { Text = option != null ? optionString + "-" + option["Text"] : optionString });
                    optionString = reportRow["S17"].ToString();
                    option = s17.GetChild(optionString);
                    recordRow.Cells.Add(new Cell() { Text = option != null ? optionString + "-" + option["Text"] : optionString });
                }
                else if (Context.CompatibleProjectName == Global.PROJECT_SATIS_SUREC)
                {
                    Tree s2 = Context.Questionnaire.GetChild("S2");
                    string optionString = reportRow["S2"].ToString();
                    Tree option = s2.GetChild(optionString);
                    recordRow.Cells.Add(new Cell() { Text = option != null ? optionString + "-" + option["Text"] : optionString });
                    Tree s8b = Context.Questionnaire.GetChild("S8b");
                    optionString = reportRow["S8b"].ToString();
                    option = s8b.GetChild(optionString);
                    recordRow.Cells.Add(new Cell() { Text = option != null ? optionString + "-" + option["Text"] : optionString });
                }
                else if (Context.CompatibleProjectName == Global.PROJECT_SSRD)
                {
                    Tree s2 = Context.Questionnaire.GetChild("S3");
                    string optionString = reportRow["S3"].ToString();
                    Tree option = s2.GetChild(optionString);
                    recordRow.Cells.Add(new Cell() { Text = option != null ? optionString + "-" + option["Text"] : optionString });
                    Tree s10 = Context.Questionnaire.GetChild("S10");
                    optionString = reportRow["S10"].ToString();
                    option = s10.GetChild(optionString);
                    recordRow.Cells.Add(new Cell() { Text = option != null ? optionString + "-" + option["Text"] : optionString });
                }
            }

            return results;
        }

        public override string DisplayName
        {
            get { return "Ses Kayıtları"; }
        }

        public override bool SupportsProject(string projectName)
        {
            return base.SupportsProject(projectName) || projectName == Global.PROJECT_SATIS_SUREC;
        }

        public override string SortPrefix
        {
            get { return "0x0C"; }
        }

        public override bool Authorized
        {
            get
            {
                return base.GetAuthLevel() != "dealer";
            }
        }
    }
}
